﻿<template>
  <s-layout title="订单详情" :bg-style="{ backgroundColor: '#f5f5f5' }">
    <view class="detail-container">
      <!-- 取餐码区域（已出码订单） -->
      <view class="pickup-code-section" v-if="showPickupCode">
        <view class="code-title">取餐码</view>
        <view class="code-number">{{ pickupCode }}</view>
        <view class="code-tip">请凭此码到门店取餐</view>
      </view>

      <!-- 订单状态 -->
      <!-- <view class="status-section">
        <view class="status-icon">
          <text class="icon-text">{{ getStatusIcon(orderInfo.orderStatus) }}</text>
        </view>
        <view class="status-text">{{ displayStatusText }}</view>
      </view> -->

      <!-- 门店信息 -->
      <view class="store-section">
        <view class="store-header">
          <view class="store-logo">
            <image :src="storeLogo" mode="aspectFill"></image>
          </view>
          <view class="store-info">
            <view class="store-name">{{ displayShopName }}</view>
            <view class="store-tag">{{ eatTypeText }}</view>
          </view>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="products-section">
        <view class="section-title">商品清单</view>
        <view class="product-item" v-for="(product, index) in orderProducts" :key="index">
          <image class="product-img" :src="getProductImage(product)" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{ getProductName(product) }}</view>
            <view class="product-spec" v-if="getProductSpec(product)">{{ getProductSpec(product) }}</view>
            <view class="product-footer">
              <view class="product-price">¥{{ formatPrice(getProductPrice(product)) }}</view>
              <view class="product-count">x{{ getProductCount(product) }}</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 金额明细 -->
      <view class="amount-section">
        <view class="section-title">金额明细</view>
        <view class="amount-item">
          <text class="amount-label">商品金额</text>
          <text class="amount-value">¥{{ formatPrice(orderInfo.totalAmount) }}</text>
        </view>
        <view class="amount-item total">
          <text class="amount-label">实付金额</text>
          <text class="amount-value highlight">¥{{ formatPrice(orderInfo.payAmount) }}</text>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-info-section">
        <view class="section-title">订单信息</view>
        <view class="info-item">
          <text class="info-label">订单编号</text>
          <view class="info-value-box">
            <text class="info-value">{{ orderInfo.orderSn }}</text>
            <text class="copy-btn" @click="copyOrderSn">复制</text>
          </view>
        </view>
        <view class="info-item">
          <text class="info-label">创建时间</text>
          <text class="info-value">{{ formatTime(orderInfo.createTime) }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.phone">
          <text class="info-label">联系电话</text>
          <text class="info-value">{{ orderInfo.phone }}</text>
        </view>
        <view class="info-item" v-if="cateringOrder.thirdOrderId">
          <text class="info-label">第三方订单号</text>
          <text class="info-value">{{ cateringOrder.thirdOrderId }}</text>
        </view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="bottom-bar" v-if="orderInfo.orderStatus === 0">
        <view class="pay-info">
          <text class="pay-label">待支付</text>
          <text class="pay-amount">¥{{ formatPrice(orderInfo.payAmount) }}</text>
        </view>
        <view class="pay-btn" @click="goPay">去支付</view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import sheep from '@/sheep';

// 数据
const orderId = ref('');
const orderInfo = ref({});
const cateringOrder = ref({});
const thirdOrderDetail = ref({});

// 默认logo
const defaultLogo = 'https://kfccatering-static.oss-cn-beijing.aliyuncs.com/logo/kfc-logo.png';

// 门店Logo
const storeLogo = computed(() => {
  const cateringStore = sheep.$store('catering');
  return cateringStore.storeInfo?.logo || defaultLogo;
});

// 用餐方式文本
const eatTypeText = computed(() => {
  const eatType = orderInfo.value.eatType;
  if (eatType === 0) return '堂食';
  if (eatType === 1) return '打包';
  if (eatType === 2) return '外卖';
  return '堂食';
});

// 是否显示取餐码
const showPickupCode = computed(() => {
  return cateringOrder.value.codes &&
      cateringOrder.value.thirdOrderStatus === '已出码';
});

// 取餐码
const pickupCode = computed(() => {
  return cateringOrder.value.codes || '';
});

// 订单商品列表 - 优先使用 localOrder 中的商品列表（包含系统内部价格）
const orderProducts = computed(() => {
  // 优先使用 localOrder 中的商品列表（包含系统内部价格）
  if (orderInfo.value.products && Array.isArray(orderInfo.value.products) && orderInfo.value.products.length > 0) {
    console.log('【订单详情】使用 localOrder 商品列表，数量:', orderInfo.value.products.length);
    return orderInfo.value.products.map(p => ({
      image: p.image,
      name: p.name,
      price: p.price, // 使用系统内部保存的售价
      count: p.count,
      specsText: p.specsText || ''
    }));
  }

  // 降级：使用第三方商品信息（仅当 localOrder 没有商品列表时）
  if (thirdOrderDetail.value.productsInfo) {
    try {
      console.log('【订单详情】使用 thirdOrderDetail 商品列表（降级）');
      const list = JSON.parse(thirdOrderDetail.value.productsInfo);
      return list.map(p => ({
        image: p.imageUrl || p.image,
        name: p.nameCn || p.name,
        price: p.selPrice || p.orgPrice || p.price,
        count: p.quantity || p.count,
        specsText: p.spec || (Array.isArray(p.selected)
            ? p.selected.map(s => (s.products && s.products[0] && s.products[0].specName) || '').filter(Boolean).join('/')
            : '')
      }));
    } catch (e) {
      console.error('【订单详情】解析商品信息失败:', e);
    }
  }

  return [];
});

// 门店名优先 thirdOrderDetail.shopName 其次 cateringOrder.shopName 再次 local
const displayShopName = computed(() => {
  return thirdOrderDetail.value.shopName || cateringOrder.value.shopName || orderInfo.value.shopName || '门店';
});

// 状态文案优先 thirdOrderDetail.orderStateName 其次 cateringOrder.thirdOrderStatus 再次本地映射
const displayStatusText = computed(() => {
  if (thirdOrderDetail.value.orderStateName) return thirdOrderDetail.value.orderStateName;
  if (cateringOrder.value.thirdOrderStatus) return cateringOrder.value.thirdOrderStatus;
  return getOrderStatusName(orderInfo.value.orderStatus);
});

// 页面加载
onLoad(async (options) => {
  if (options.orderId) {
    orderId.value = options.orderId;
    await loadOrderDetail();
  } else {
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载订单详情
async function loadOrderDetail() {
  try {
    uni.showLoading({ title: '加载中...' });

    const res = await sheep.$api.catering.getOrderDetail(orderId.value);

    uni.hideLoading();

    if (res.code === 200 && res.data) {
      orderInfo.value = res.data.localOrder || {};
      cateringOrder.value = res.data.cateringOrder || {};
      thirdOrderDetail.value = res.data.thirdOrderDetail || {};

      console.log('【订单详情】订单数据:', {
        orderInfo: orderInfo.value,
        cateringOrder: cateringOrder.value,
        thirdOrderDetail: thirdOrderDetail.value
      });

      // 同步数据
      if (orderInfo.value.codes && !cateringOrder.value.codes) {
        cateringOrder.value.codes = orderInfo.value.codes;
      }

      if (orderInfo.value.thirdOrderStatus && !cateringOrder.value.thirdOrderStatus) {
        cateringOrder.value.thirdOrderStatus = orderInfo.value.thirdOrderStatus;
      }

      if (orderInfo.value.shopName && !cateringOrder.value.shopName) {
        cateringOrder.value.shopName = orderInfo.value.shopName;
      }
    } else {
      uni.showToast({
        title: res.msg || '加载失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【订单详情】加载订单详情失败:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    });
  }
}

// 格式化价格
function formatPrice(price) {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 复制订单号
function copyOrderSn() {
  if (!orderInfo.value.orderSn) {
    uni.showToast({
      title: '订单号不存在',
      icon: 'none'
    });
    return;
  }

  uni.setClipboardData({
    data: orderInfo.value.orderSn,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      });
    }
  });
}

// 去支付
function goPay() {
  sheep.$router.go('/pages/catering/order-pay', {
    orderId: orderId.value
  });
}

// 获取商品名称
function getProductName(product) {
  return product.name || product.productName || product.title || '商品';
}

// 获取商品图片
function getProductImage(product) {
  return product.image || product.pic || product.productImage || 'https://static.cdn.23kfc.com/img/default-product.png';
}

// 获取商品规格文本
function getProductSpec(product) {
  if (product.specsText) return product.specsText;

  if (product.selected && Array.isArray(product.selected)) {
    return product.selected.map(s => s.name || s.value).filter(Boolean).join('/');
  }

  if (product.selectedSpecs && typeof product.selectedSpecs === 'object') {
    return Object.values(product.selectedSpecs).filter(Boolean).join('/');
  }

  return '';
}

// 获取商品价格
function getProductPrice(product) {
  return product.price || product.salePrice || product.productPrice || 0;
}

// 获取商品数量
function getProductCount(product) {
  return product.count || product.quantity || product.num || 1;
}

// 获取订单状态名称
function getOrderStatusName(status) {
  const statusMap = {
    0: '等待支付',
    1: '待核销',
    3: '已出码',
    6: '订单退款',
    7: '超时未付',
    8: '订单成功(部分退款)',
    12: '配送中',
  };
  return statusMap[status] || '未知状态';
}

// 获取订单状态图标
function getStatusIcon(status) {
  const iconMap = {
    0: '⏰',
    1: '✅',
    3: '🎫',
    6: '💰',
    7: '❌',
    8: '✅',
    12: '🚗',
  };
  return iconMap[status] || '📋';
}
</script>

<style lang="scss" scoped>
.detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 180rpx;
}

// 取餐码区域
.pickup-code-section {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  padding: 50rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;

  .code-title {
    color: #fff;
    font-size: 28rpx;
    margin-bottom: 20rpx;
    opacity: 0.9;
  }

  .code-number {
    color: #fff;
    font-size: 72rpx;
    font-weight: bold;
    letter-spacing: 8rpx;
    margin-bottom: 15rpx;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  }

  .code-tip {
    color: #fff;
    font-size: 24rpx;
    opacity: 0.8;
  }
}

// 订单状态区域
.status-section {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  padding: 24rpx 24rpx;
  text-align: center;
  margin-bottom: 12rpx;

  .status-icon {
    margin-bottom: 8rpx;

    .icon-text {
      font-size: 40rpx;
    }
  }

  .status-text {
    color: #fff;
    font-size: 26rpx;
    font-weight: bold;
  }
}

// 门店信息
.store-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .store-header {
    display: flex;
    align-items: center;

    .store-logo {
      width: 100rpx;
      height: 100rpx;
      border-radius: 10rpx;
      overflow: hidden;
      margin-right: 20rpx;
      flex-shrink: 0;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .store-info {
      flex: 1;

      .store-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }

      .store-tag {
        display: inline-block;
        padding: 4rpx 12rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        border-radius: 4rpx;
      }
    }
  }
}

// 商品列表
.products-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .product-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .product-img {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
      flex-shrink: 0;
      margin-right: 20rpx;
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .product-name {
        font-size: 28rpx;
        color: #333;
        line-height: 1.4;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .product-spec {
        font-size: 24rpx;
        color: #999;
        margin-top: 8rpx;
      }

      .product-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10rpx;

        .product-price {
          font-size: 28rpx;
          color: #e4393c;
          font-weight: bold;
        }

        .product-count {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

// 金额明细
.amount-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .amount-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;

    &.total {
      padding-top: 20rpx;
      border-top: 1rpx solid #f0f0f0;
    }

    .amount-label {
      font-size: 28rpx;
      color: #666;
    }

    .amount-value {
      font-size: 28rpx;
      color: #333;

      &.highlight {
        font-size: 32rpx;
        font-weight: bold;
        color: #e4393c;
      }
    }
  }
}

// 订单信息
.order-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .info-item {
    display: flex;
    align-items: center;
    padding: 15rpx 0;

    .info-label {
      width: 200rpx;
      font-size: 28rpx;
      color: #999;
      flex-shrink: 0;
    }

    .info-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }

    .info-value-box {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .info-value {
        flex: 1;
        font-size: 28rpx;
        color: #333;
        word-break: break-all;
      }

      .copy-btn {
        padding: 4rpx 16rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        border-radius: 4rpx;
        margin-left: 10rpx;
        flex-shrink: 0;
      }
    }
  }
}

// 底部支付栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;

  .pay-info {
    .pay-label {
      display: block;
      font-size: 24rpx;
      color: #999;
      margin-bottom: 5rpx;
    }

    .pay-amount {
      font-size: 36rpx;
      font-weight: bold;
      color: #e4393c;
    }
  }

  .pay-btn {
    background: linear-gradient(135deg, #ff6b6b 0%, #e74c3c 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 50rpx;
    padding: 20rpx 60rpx;
  }
}
</style>
